package web

import (
	"github.com/kardianos/service"
	_ "go-iot-project/docs"
	"go-iot-project/internal/args"
	"go-iot-project/internal/initialize"
	"go-iot-project/iothub"
	"go-iot-project/pkg/cache"
	"go-iot-project/pkg/config"
	"go-iot-project/pkg/db"
	"os"
	"os/signal"
	"syscall"
)

type Program struct{}

func (p *Program) Start(s service.Service) error {
	go p.run()
	return nil
}

func (p *Program) run() {
	hup := make(chan os.Signal, 2)
	signal.Notify(hup, syscall.SIGHUP)

	quit := make(chan os.Signal, 2)
	signal.Notify(quit, os.Interrupt, os.Kill)

	config.InitConfig(args.ConfigPath)
	// 初始化mqtt
	//mqttHook := &initialize.IotMqttHook{}
	//var hook = mqtt.HookBase{}
	var hook = &initialize.IotMqttHook{}
	_ = iothub.InitMqtt(config.Engine.MqttConfig, hook)
	db.Open(config.Engine.MySql)

	cache.InitRedis(config.Engine.Redis)

	initialize.InitTable(db.MyDb)
	go func() {
		for {
			select {
			case <-hup:
			case <-quit:
				//优雅地结束
				os.Exit(0)
			}
		}
	}()

	engine := CreateEngine()
	RegisterSwaggerDocs(&engine.RouterGroup, "swagger")
	Startup(engine)
	engine.Serve()
}

func (p *Program) Stop(s service.Service) error {
	cache.Close()
	iothub.Close()
	return nil
}
